package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.Node;
import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysMenu;
import com.cy.pj.sys.pojo.SysUserMenu;
import com.cy.pj.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @Autowired
    SysUserRoleDao sysUserRoleDao;

    //@RequiredLog("查询菜单")
    @Override
    public List<Map<String, Object>> findObjects() {
        return sysMenuDao.findObjects();
    }

    @Override
    public List<SysUserMenu> findUserMenusByUserId(Integer id) {
        //1.对用户id进行判断
        //2.基于用户id查找用户对应的角色id
        List<Integer> roleIds=
                sysUserRoleDao.findRoleIdsByUserId(id);
        //3.基于角色id获取角色对应的菜单信息,并进行封装.
        List<Integer> menuIds=
                sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
        //4.基于菜单id获取用户对应的菜单信息并返回
        return sysMenuDao.findMenusByIds(menuIds);
    }

    @Override
    public int deleteObject(Integer id) {
        if (id == null || id < 1) {
            throw new IllegalArgumentException("id值无效");
        }
        int childCount = sysMenuDao.getChildCount(id);
        if (childCount > 0) {
            throw new ServiceException("请先删除子菜单");
        }
        //删除关系数据
        sysRoleMenuDao.deleteObjectsByMenuId(id);
        int rows = sysMenuDao.deleteObject(id);
        if (rows == 0) {
            throw new ServiceException("记录可能已经不存在了");
        }
        return rows;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuDao.findZtreeMenuNodes();
    }

    @Override
    public int saveObject(SysMenu entity) {
        if (entity == null) {
            throw new IllegalArgumentException("保存对象不能为空");
        }
        if (StringUtils.isEmpty(entity.getName())) {
            throw new IllegalArgumentException("菜单名不能为空");
        }
        int rows = sysMenuDao.insertObject(entity);
        return rows;
    }

    @Override
    public int updateObject(SysMenu entity) {
        if (entity == null) {
            throw new IllegalArgumentException("保存对象不能为空");
        }
        if (StringUtils.isEmpty(entity.getName())) {
            throw new IllegalArgumentException("菜单名不能为空");
        }
        int rows = sysMenuDao.updateObject(entity);
        if (rows == 0) {
            throw new ServiceException("记录可能已经不存在");
        }
        return rows;
    }
}
